package com.cbs.java.component.network.decoder;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;
import okhttp3.ResponseBody;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;

/**
 * Created by broche on 10/7/15.
 */
public class GsonDecoder implements Decoder {
    private static final Logger L = Logger.getLogger(GsonDecoder.class);
    private String charset = "UTF-8";
    private Gson gson = new Gson();
    private Type aType = null;

    public GsonDecoder(Type aType) {
        super();
        this.aType = aType;
    }

    public GsonDecoder(Class aClass) {
        super();
        this.aType = aClass;
    }

    public GsonDecoder(Type aType, String charset) {
        this.charset = charset;
        this.aType = aType;
    }

    public GsonDecoder(Class aClass, String charset) {
        this.charset = charset;
        this.aType = aClass;
    }

    public GsonDecoder enablePrettyPrinting() {
        gson = new GsonBuilder().setPrettyPrinting().create();
        return this;
    }

    public Object decode(ResponseBody body) throws IOException {
        Object result = null;
        try {
            if (aType != null) {
                result = gson.fromJson(new JsonReader(new InputStreamReader(body.byteStream(), charset)), aType);
            } else {
                result = null;
            }
        } catch (Exception e) {
            L.error("", e);
        }
        return result;
    }

    @Override
    public String desc(Object result) {
        if (result != null) {
            String desc = gson.toJson(result);
            return String.format("json(%d): %s", desc.length(), desc);
        } else {
            return "json: null";
        }
    }
}
